from PyPDF4 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from PIL import Image
import io


def create_pdf_with_image(image_path, output_pdf):
    """创建一个包含单张图片的PDF文件"""
    img = Image.open(image_path)
    width, height = img.size

    # Create a byte stream for the PDF
    packet = io.BytesIO()

    # Create a new PDF with Reportlab
    can = canvas.Canvas(packet, pagesize=A4)
    can.drawImage(image_path, 0, 0, width=A4[0], height=A4[1])  # Adjust image size to fit page
    can.showPage()
    can.save()

    # Move to the beginning of the StringIO buffer
    packet.seek(0)

    # Create a PDF reader object
    new_pdf = PdfFileReader(packet)
    return new_pdf


def merge_pdfs_with_images(image_paths, output_pdf):
    """将多张图片转换为PDF并合并成一个PDF文件"""
    pdf_writer = PdfFileWriter()

    for image_path in image_paths:
        pdf_page = create_pdf_with_image(image_path, None)
        pdf_writer.addPage(pdf_page.pages[0])

    # Write out the merged PDF
    with open(output_pdf, "wb") as out_file:
        pdf_writer.write(out_file)


if __name__ == "__main__":
    images = ["1.jpg", "2.jpg"]  # 替换为你的图片路径
    output_file = "output.pdf"
    merge_pdfs_with_images(images, output_file)
    print(f"PDF created: {output_file}")
